﻿/// <reference name="MicrosoftAjax.js"/>

var _tblId = '';
var _department_code = '';
var cObjMasterType;
var cObjMainSystem;
var cObjMenuSystem;
var cObjSubMenu;
var cAuthDepartment;
var _saveService = "../WebService.asmx/SaveAuthenDepartmentObject";
var _loadService = "../WebService.asmx/GetAuthenDepartmentObject"; ///
var _goService = "../WebService.asmx/GetDestination";


function markRow(objCheckbox) {

        $(objCheckbox)
            .parent()
            .parent()
            .find(':input')
            .filter(':checkbox')
            .not('input[disabled=disabled]')
            .attr('checked', $(objCheckbox).attr('checked'));
            
}


function loadAuthDepartmentObject(p_main_system_code,p_department_code,pnlId) {

    var xdoc = $.ajax({
        url: _loadService,
        global: false,
        type: "POST",
        data: ({ main_system_code: p_main_system_code, department_code: p_department_code }),
        dataType: "script",
        async: false
    }
    ).responseXML;

    //Generate table
    $('#' + pnlId).html(generateUI(xdoc.text));

}

function saveAuth() {

    var cDepartment = [];
    $('#ctl00_cphBody_Uc_stp_auth_department_fv1_lbDepartment :selected').each(function(i, selected) {
        cDepartment[i] = $(selected).val();
    });
    var count = cDepartment.length;

    for (i in cDepartment) {

        for (j in cAuthDepartment)
        {
            cAuthDepartment[j].department_code = cDepartment[i];
        }

        var jstring = YAHOO.lang.JSON.stringify(cAuthDepartment);
        var xdoc = $.ajax({
            url: _saveService,
            global: false,
            type: "POST",
            data: ({ jdata: jstring }),
            dataType: "script",
            async: false,
            success: function() {
                
                count--;
                if (count <= 0) {
                    alert('ข้อมูลถูกบันทึกแล้ว')
                }
                
            }
        })
        
    }



}




function embedData(objData) {

    objData = eval('(' + objData + ')');


}

function hasAuthObject(cAuthDepartment,sub_menu_code) {

    for (idx in cAuthDepartment)
    {
        if (cAuthDepartment[idx].sub_menu_code == sub_menu_code) {
            return true;
        }
    }
    return false;
}

//call service
function generateUI(objData) {

    objData = eval('(' + objData  + ')');

    var strUi = '';
    var countColumn = 0;
    
    //Store data to client.
    cObjMasterType = objData.MasterTypes;
    cObjMainSystem = objData.MainSystems;
    cObjMenuSystem = objData.MenuSystems;
    cObjSubMenu = objData.SubMenus;
    cAuthDepartment = objData.AuthDepartments;

    _department_code = objData.Department_code;

    strUi += '<table id="' + _tblId + '"  cellspacing="2" cellpadding="2" bordercolor="#999999" border="0" align="center" width="100%">';

    //Generate Header
    strUi += '<tbody><tr bgcolor="#ff9999" align="center"  class="component_caption"><td  class="th_data" colspan="2">ระบบ/เมนูระบบ</td>';
    $.map(cObjMasterType, function(n, i) {

    strUi += String.format('<td class="th_data">{0}</td>', n.type_name);
        countColumn++;
    })
    strUi += '</tr>';


    //Generate Body
    for (main in cObjMainSystem)
    {

        //Main system
        strUi += '<tr>';
        strUi += String.format('<td bgcolor="#D8D8D8"  colspan="2">{0}</td>', cObjMainSystem[main].main_system_name)
        for (iLoop = 0; iLoop < countColumn; iLoop++) {
            strUi += String.format('<td bgcolor="#D8D8D8" width="80px">&nbsp;</td>');
        }
        strUi += '</tr>';

        //Menu System
        for (menu in cObjMenuSystem){
            
            if (cObjMainSystem[main].main_system_code == cObjMenuSystem[menu].main_system_code) {
                
                //Create menu label
                strUi += '<tr>';
//                strUi += String.format("<td><input type='checkbox' onclick='markRow(this)' /></td>");
                //                strUi += String.format("<td>{0}</td>", cObjMenuSystem[menu].menu_system_name);
                strUi += String.format("<td colspan='2'>{0}</td>", cObjMenuSystem[menu].menu_system_name);
                
                for (mtype in cObjMasterType){

                    strUi += "<td align='center' class='td_data' bordercolor='#CCCCCC'>";
                    
                    for (sub in cObjSubMenu) {

                        if (cObjSubMenu[sub].menu_system_code == cObjMenuSystem[menu].menu_system_code) {
                           if (cObjSubMenu[sub].type_code == cObjMasterType[mtype].type_code) {
//                                var hasAuth = hasAuthObject(cAuthDepartment, cObjSubMenu[sub].sub_menu_code);
//                                var cbData = String.format(
//                                '<input class="cb_data" {1} onclick="updateAuthObject({0},this)" type="checkbox" />',
//                                cObjSubMenu[sub].sub_menu_code,
//                                hasAuth == true ? "checked='checked'" : ""
//                            );
//

//                             var cbData = String.format('[ <a href="main_system_fv.aspx?Edit={0}">คลิ๊ก</a> ]', queryString('Edit'));
//                            strUi += String.format("{0}", cbData);

                                var cbData = String.format('[ <a onclick="goDestination({0})" href="#">คลิ๊ก</a> ]',cObjSubMenu[sub].sub_menu_code );
                                strUi += String.format("{0}", cbData);

                         }
                  

                        }

                    };

                    strUi += "&nbsp;</td>";

                }
                
                strUi += '</tr>';
            }

        }

    };

    strUi += String.format(
                    '<tr><td align="center" bgcolor="#ffffff" class="td_data_end col_delete" colspan="{0}"><center><button onclick="saveAuth()" type="button">บันทึกข้อมูล</button><button type="reset">ยกเลิก</button></center></td></tr>', 
                    countColumn + 2);
    strUi += "</tbody></table>"
    
    
    
    //jObjMasterType, jObjContent
    /*
    {type_code,type_name}  master_tyee
    {main_system_code,main_system_name,department_code}
    {sub_menu_code,type_code,}
    */

    return strUi;
}





function removeAuthObject(cAuthDepartment, sub_menu_code) {
    for (idx in cAuthDepartment) {
        if (cAuthDepartment[idx].sub_menu_code == sub_menu_code) {
            Array.removeAt(cAuthDepartment, idx);
        }
    }
}

function updateAuthObject(sub_menu_code,objCheckbox) {

    //remove object
    removeAuthObject(cAuthDepartment, sub_menu_code)
    if ($(objCheckbox).attr('checked') == true) {

        //Add auth object
        Array.add(
            cAuthDepartment,
            {
                auth_department_code: 9999,
                department_code: _department_code,
                sub_menu_code: sub_menu_code
            }

        );

    }

    

}


function goDestination(p_sub_menu_code)
{

     var xdoc = $.ajax({
        url: _goService,
        global: false,
        type: "POST",
        data: ({ sub_menu_code: p_sub_menu_code }),
        dataType: "script",
        async: false
    }
    ).responseXML;

    //Generate table
    //$('#' + pnlId).html(generateUI(xdoc.text));   

    var objData = eval('(' + xdoc.text  + ')');


    window.open(objData.StpSubMenu[0].sub_menu_url, '_self');
    
    
}



